<?php
class LetterOut extends AppModel {
    var $validate = array(
        'unit_code_id' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => array('vUnit'),
            'message' => 'Pilih berdasarkan opsi yang tersedia'
        ),
        'term_code_id' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => array('vTerm'),
            'message' => 'Pilih berdasarkan opsi yang tersedia'
        ),
        'letter_date' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => array('date'),
            'message' => 'Harap isi dengan tanggal yang valid'
        ),
        'letter_to' => array(
            'required' => array(
                'required' => true,
                'allowEmpty' => false,
                'rule' => '/^\w+[\w\s]?/',
                'message' => 'Tidak boleh kosong'
            )
        )
    );

    var $belongsTo = array(
        'UnitCode',
        'TermCode',
        'LetterNumber',
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'created_by',
            'fields' => array('id', 'name')
        )
    );
    
    var $hasMany = array(
        'LetterOutImage' => array(
            'dependent' => true
        )
    );

    var $cacheQueries = true;
    
    function beforeSave() {
        if ( isset($this->data[$this->name]['modified_by']) ) { // edit action
            
        } else { //add action
            // find active number
            $activeNumber = $this->LetterNumber->find('first', array(
                'conditions' => array(
                    'LetterNumber.active' => 1
                ),
                'fields' => array('id', 'no_start', 'no_end'),
                'recursive' => -1,
                'order' => array('LetterNumber.created DESC')
            ));
            
            if ( empty($activeNumber) ) {
                /**
                 * TODO: send email notification to admin
                 */
                $this->validationErrors['letter_no'] = 'There is no active letter number. Contact your administrator to fix this';
                return false;
            }
            
            // find letter-outs that use active number
            $lastLetter = $this->find('first', array(
                'conditions' => array(
                    $this->name . '.letter_number_id' => $activeNumber['LetterNumber']['id']
                ),
                'fields' => array('counter'),
                'recursive' => -1,
                'order' => array($this->name . '.letter_number_id DESC', $this->name . '.counter DESC', $this->name . '.created DESC')
            ));
            
            if ( !empty($lastLetter) ) {
                // this active number already used by letter outs
                // first make sure last counter between no_start
                // and no_end of active number
                if ( $lastLetter['LetterOut']['counter'] == $activeNumber['LetterNumber']['no_end'] ) {
                    /**
                     * TODO: send email notification to admin
                     */
                    $this->validationErrors['letter_no'] = 'Number is exceeding the maximum. Contact your administrator to fix this';
                    return false;
                } else {
                    // we now can safely increment last letter out counter
                    // and set it to newly created letter
                    $this->data[$this->name]['counter'] = $lastLetter['LetterOut']['counter'] + 1;
                }
                
            } else {
                // there is no letter out uses this 
                // active number, so we can set first letter
                // counter to no_start of active number
                $this->data[$this->name]['counter'] = $activeNumber['LetterNumber']['no_start'];
            }
            
            // set active number used by letter
            $this->data[$this->name]['letter_number_id'] = $activeNumber['LetterNumber']['id'];
            
            // prepare for counter number
            $counter = $this->data[$this->name]['counter'];
            $lenNo = strlen($activeNumber['LetterNumber']['no_end']);
            
            // get unit code
            $unit = $this->UnitCode->find('first', array(
                'conditions' => array(
                    'UnitCode.id' => $this->data[$this->name]['unit_code_id']
                ),
                'fields' => array('UnitCode.code'),
                'recursive' => -1
            ));
            // get term code
            $term = $this->TermCode->find('first', array(
                'conditions' => array(
                    'TermCode.id' => $this->data[$this->name]['term_code_id']
                ),
                'fields' => array('TermCode.code'),
                'recursive' => -1
            ));
            
            // check pad zero
            if ( isset($this->data[$this->name]['pad']) && $this->data[$this->name]['pad'] ) {
                $counter = str_pad($counter, $lenNo, '0', STR_PAD_LEFT);
            }

            // now, time to generate letter no
            $this->data[$this->name]['letter_no'] = $counter . '/' . $unit['UnitCode']['code'] .
                    '/' . $term['TermCode']['code'] . '/' . $this->getMonthGreek() . '/' . date('Y');
                    
        }
        return true;
    }
    
    function vUnit($field) {
        $exist = $this->UnitCode->find('count', array(
            'conditions' => array(
                'UnitCode.id' => $field["unit_code_id"]
            ),
            'recursive' => -1)
        );
        return $exist > 0;
    }
    
    function vTerm($field) {
        $exist = $this->TermCode->find('count', array(
            'conditions' => array(
                'TermCode.id' => $field["term_code_id"]
            ),
            'recursive' => -1)
        );
        return $exist > 0;
    }
    
    function getMonthGreek() {
        switch ( date('n') ) {
            case 1: return 'I';
            case 2: return 'II';
            case 3: return 'III';
            case 4: return 'IV';
            case 5: return 'V';
            case 6: return 'VI';
            case 7: return 'VII';
            case 8: return 'VIII';
            case 9: return 'IX';
            case 10: return 'X';
            case 11: return 'XI';
            case 12: return 'XII';
            default: return '';
        }
    }

/**
 * Qty per month based on year and whom create that (user or unit)
 * used by ReportsController::grafik
 * $per null means all unit codes
 */
    function getQtyPerMonth($year, $by, $per = null) {
        $WHERE = ' WHERE ';
        if ( $by == 'u' ) {
            if ( $per ) {
                $WHERE .=  "unit_code_id = $per ";
            } else {
                $WHERE .= "1=1 ";
            }
        } else {
            if ( $per ) {
                $WHERE .=  "created_by = $per ";
            } else {
                $WHERE .= "1=1 ";
            }
        }
        
        $WHERE .= "AND created >= '$year-01-01 00:00:00' AND created <= '$year-12-31 23:59:59'";
        
        return $this->query("SELECT COUNT(id) as qty, DATE_FORMAT(created, '%m') as m FROM `letter_outs` $WHERE  GROUP BY m");
    }
}
?>
